package com.taotao.wechat.business;

import com.taotao.wechat.menu.Menu;
import org.springframework.http.HttpEntity;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;

public class MenuUtil {
    private static final String create_menu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

    public static boolean generateMenu(Menu menu, String appId){
        HttpEntity request = new HttpEntity(menu);
        RestTemplate restTemplate = new RestTemplate();
        LinkedHashMap<String, Object> result = restTemplate.postForObject(create_menu_url.replace("ACCESS_TOKEN", new Accesstoken(appId).getAccesstoken()),
                request, LinkedHashMap.class);

        boolean isGenerate = result.get("errcode") != null && "0".equalsIgnoreCase(result.get("errcode").toString());
        if (!isGenerate) {
            result = restTemplate.postForObject(create_menu_url.replace("ACCESS_TOKEN", new Accesstoken(appId).updateAccesstoken()),
                    request, LinkedHashMap.class);
            return result.get("errcode") != null && "0".equalsIgnoreCase(result.get("errcode").toString());
        }
        return true;
    }
}
